//
//  WSHeaderView.m
//  LANGirl
//
//  Created by 吴帅 on 16/3/28.
//
//

#import "WSMineHeaderView.h"
#import "WSMineHeadSubView.h"
#import <Accelerate/Accelerate.h>

@interface WSMineHeaderView (){

    CGRect tempFrame;
}

@property (nonatomic, strong) UIImageView *userHeadView;
@property (nonatomic, strong) UIImageView *certifyView;
@property (nonatomic, strong) UILabel *userNameLabel;
@property (nonatomic, strong) UILabel *numberLabel;
@property (nonatomic, strong) WSMineHeadSubView *subCVView;
@property (nonatomic, strong) WSMineHeadSubView *subTalkView;
@property (nonatomic, strong) WSMineHeadSubView *subCollectView;
@property (nonatomic, strong) UIView *wBlackView;

@end

@implementation WSMineHeaderView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        tempFrame = CGRectMake(0, 0, SCREEN_WIDTH, 282 * AUTO_HEIGHT);
        self.backgroundColor = [UIColor whiteColor];
        [self createSubView];
        [self creatrLi];
    }
    return self;
}

- (void)createSubView {

    self.imageScrollView = [[UIScrollView alloc] initWithFrame:tempFrame];
    [self addSubview:self.imageScrollView];
    
    UIImage *image = [UIImage imageNamed:@"headBackImage"];
    //添加底图
    self.headImageView=[[UIImageView alloc]initWithFrame:self.imageScrollView.bounds];
    self.headImageView.center = CGPointMake(self.center.x, self.headImageView.center.y);
    self.headImageView.userInteractionEnabled=YES;
    self.headImageView.layer.masksToBounds = YES;
    self.headImageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    UITapGestureRecognizer *detailTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:nil];
    [self.headImageView addGestureRecognizer:detailTap];
    self.headImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.headImageView.image = image;
    
    //高斯背景
    self.imageBackgroundView = [[UIImageView alloc] initWithFrame:self.headImageView.bounds];
    self.imageBackgroundView.image = image;
    self.imageBackgroundView.layer.masksToBounds = YES;
    [self setBlurryImage:image];
    self.imageBackgroundView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.imageBackgroundView.contentMode = UIViewContentModeScaleAspectFill;
    [self.imageScrollView addSubview:self.imageBackgroundView];
    [self.imageScrollView addSubview:self.headImageView];
    
    
    
    self.wBlackView = [[UIView alloc]init];
    self.wBlackView.backgroundColor=[UIColor whiteColor];
    self.wBlackView.alpha=0.21;
    [self addSubview:self.wBlackView];
    [self.wBlackView mas_makeConstraints:^(MASConstraintMaker *make){
        
        make.left.mas_equalTo(@0);
        make.bottom.mas_equalTo(-(360 - 282) * AUTO_HEIGHT);
        make.size.mas_equalTo(CGSizeMake(self.frame.size.width, 95.00*AUTO_WIDTH));
    }];
    
    //头像的定义
    self.userHeadView = [[UIImageView alloc]init];
    self.userHeadView.userInteractionEnabled = YES;
    self.userHeadView.backgroundColor = [UIColor redColor];
    self.userHeadView.image = [UIImage imageNamed:@"headBackImage"];
    self.userHeadView.layer.cornerRadius = 73.00 * AUTO_WIDTH/2;
    self.userHeadView.layer.masksToBounds = YES;
    [self addSubview:_userHeadView];
    [self.userHeadView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.wBlackView.mas_bottom).offset(-26.00*AUTO_WIDTH/2);
        make.left.mas_equalTo(30.00*AUTO_WIDTH/2);
        make.size.mas_equalTo(CGSizeMake(73.00*AUTO_WIDTH,73.00*AUTO_WIDTH ));
        
    }];
    
    
    //未认证
    self.certifyView = [[UIImageView alloc]init];
    self.certifyView.image = [UIImage imageNamed:@"header_testInfo_yes"];
    [self addSubview:_certifyView];
    [self.certifyView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.equalTo(self.wBlackView.mas_bottom).offset(20.00*AUTO_WIDTH/2);
        make.left.equalTo(_userHeadView.mas_right).offset((15.00*AUTO_WIDTH)/2);
        make.size.mas_equalTo(CGSizeMake(84.00*AUTO_WIDTH, 84.00*AUTO_WIDTH));
        
    }];
    
    
    //张三丰
    self.userNameLabel = [[UILabel alloc] init];
    self.userNameLabel.text = @"张三丰";
    self.userNameLabel.textColor = [UIColor whiteColor];
    self.userNameLabel.font = [UIFont systemFontOfSize:TEXTNAMEFONT * TEXTWEIGHT];
    [self addSubview:_userNameLabel];
    [self.userNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.equalTo(self.certifyView.mas_top).offset(30 * AUTO_WIDTH / 2);
        make.left.equalTo(_userHeadView.mas_right).offset(20  * AUTO_WIDTH / 2);
        make.size.mas_equalTo(CGSizeMake((self.userNameLabel.text.length * ONETEXTWIDTH * AUTO_WIDTH), ONETEXTWIDTH * AUTO_WIDTH));
    }];
    
    
    //笔的图片
    UIImageView *wrightIM= [[UIImageView alloc]init];
    wrightIM.image = [UIImage imageNamed:@"mine_edit"];
    [self addSubview:wrightIM];
    [wrightIM mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.equalTo(self.certifyView.mas_top).offset(30.00*AUTO_WIDTH/2);
        make.left.equalTo(self.userNameLabel.mas_right).offset(10.00*AUTO_WIDTH/2);
        make.size.mas_equalTo(CGSizeMake((15.00)*AUTO_WIDTH, 15.00*AUTO_WIDTH));
        
    }];
    
    UIButton *actionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self addSubview:actionBtn];
    [actionBtn addTarget:self action:@selector(touxiang) forControlEvents:UIControlEventTouchUpInside];
    [actionBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.top.bottom.equalTo(self.userHeadView);
        make.right.equalTo(self.certifyView);
    }];
    
    
    UIImageView *imageView1 = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"虚线竖"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]];
    imageView1.tintColor = [UIColor whiteColor];
    [self addSubview:imageView1];
    [imageView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.equalTo(self.wBlackView.mas_bottom).offset(-15.00 * AUTO_WIDTH);
        make.right.equalTo(self.mas_right).offset(-130.00 * AUTO_WIDTH);
        make.size.mas_equalTo(CGSizeMake(1.00, 64.00 * AUTO_WIDTH));
    }];
    
    
    //1061
    UILabel *scoreLabel = [[UILabel alloc]init];
    scoreLabel.text = @"375";
    scoreLabel.font = [UIFont fontWithName:@"FZLTXIHK--GBK1-0" size:30.00*TEXTWEIGHT];
    
    //金币
    UIImageView *fenImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"headerPoints"]];
    [self addSubview:fenImage];
    [fenImage mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(self.wBlackView);
        make.right.equalTo(self.mas_right).offset(-15.00*AUTO_WIDTH);
        make.size.mas_equalTo(CGSizeMake(20.00*AUTO_WIDTH, 20.00*AUTO_WIDTH));
        
    }];
    
    scoreLabel.userInteractionEnabled=YES;
    UITapGestureRecognizer *fentap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(scoreAction:)];
    [scoreLabel addGestureRecognizer:fentap];
    scoreLabel.textColor = [UIColor whiteColor];
    scoreLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview:scoreLabel];
    [scoreLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(self.wBlackView);
        make.right.equalTo(fenImage).offset(-5.00*AUTO_WIDTH);
        make.left.equalTo(imageView1.mas_right);
        make.height.mas_equalTo(64.00 * AUTO_WIDTH);
        
    }];
}

- (void)creatrLi
{

    self.subCVView = [[WSMineHeadSubView alloc] init];
    self.subTalkView = [[WSMineHeadSubView alloc] init];
    self.subCollectView = [[WSMineHeadSubView alloc] init];
    NSArray *viewArr = [NSArray arrayWithObjects:self.subCVView, self.subTalkView, self.subCollectView, nil];
    
    for (int i = 0; i < viewArr.count; i++) {
        
        WSMineHeadSubView *view = viewArr[i];
        [self addSubview:view];
        view.type = BUTTONTYPECV + i;
        view.tag = MINEHEADERSELECTWORK + i;
        view.numberStr = @"1234";
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(subViewAction:)];
        [view addGestureRecognizer:tap];
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.mas_equalTo(SCREEN_WIDTH / 3 * i);
            make.bottom.mas_equalTo(@0);
            make.top.equalTo(self.wBlackView.mas_bottom);
            make.width.mas_equalTo(SCREEN_WIDTH / 3);
        }];
    }
    
    UILabel *xiLine = [[UILabel alloc] init];
    xiLine.backgroundColor =[UIColor grayColor];
    [self addSubview:xiLine];
    xiLine.alpha = 0.2;
    [xiLine mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.equalTo(self.mas_bottom);
        make.left.equalTo(self.mas_left).offset(0);
        make.right.equalTo(self.mas_right).offset(0);
        make.height.mas_equalTo(1);
    }];
}

- (void)subViewAction:(UITapGestureRecognizer *)tap {

    UIView *view = tap.view;
    [self.delegate pushDetailViewController:view.tag];
}

- (void)touxiang {

    [self.delegate pushDetailViewController:MINEHEADERSELECTHEADER];
}

- (void)scoreAction:(UIButton *)btn {

    [self.delegate pushDetailViewController:MINEHEADERSELECTSCORE];
}

#pragma mark -- 高斯效果
/**
 *  通过scrollview的滑动改变顶部view的大小和高斯效果
 *
 *  @param offset scrollview下滑的距离
 */
- (void)updateHeaderView:(CGPoint)offset {
   
    if (offset.y < 0) {
        CGRect rect = CGRectMake(0, 0, tempFrame.size.width, tempFrame.size.height);
        CGFloat delta = fabs(MIN(0.0f, offset.y));
        rect.origin.y -= delta;
        rect.size.height += delta;
        self.imageScrollView.frame = rect;
        self.clipsToBounds = NO;
        
        self.headImageView.alpha = fabs(offset.y / (2 * CGRectGetHeight(self.bounds) / 3));
    }
}


/**
 *  高斯图片
 *
 *  @param originalImage 需要高斯的图片
 */
- (void)setBlurryImage:(UIImage *)originalImage {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        UIImage *blurredImage = [self blurryImage:originalImage withBlurLevel:0.2];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.headImageView.alpha = 0.0;
            self.imageBackgroundView.image = blurredImage;
        });
    });
    
}
/**
 *  高斯背景
 *
 *  @param image    需要高斯模糊的图片
 *  @param blur     高斯模糊的值
 *
 *  @return
 */
- (UIImage *)blurryImage:(UIImage *)image withBlurLevel:(CGFloat)blur {
    if ((blur < 0.0f) || (blur > 1.0f)) {
        blur = 0.5f;
    }
    
    int boxSize = (int)(blur * 100);
    boxSize -= (boxSize % 2) + 1;
    
    CGImageRef img = image.CGImage;
    
    vImage_Buffer inBuffer, outBuffer;
    vImage_Error error;
    void *pixelBuffer;
    
    CGDataProviderRef inProvider = CGImageGetDataProvider(img);
    CFDataRef inBitmapData = CGDataProviderCopyData(inProvider);
    
    inBuffer.width = CGImageGetWidth(img);
    inBuffer.height = CGImageGetHeight(img);
    inBuffer.rowBytes = CGImageGetBytesPerRow(img);
    inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData);
    
    pixelBuffer = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img));
    
    outBuffer.data = pixelBuffer;
    outBuffer.width = CGImageGetWidth(img);
    outBuffer.height = CGImageGetHeight(img);
    outBuffer.rowBytes = CGImageGetBytesPerRow(img);
    
    error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
    
    
    if (error) {
        NSLog(@"error from convolution %ld", error);
    }
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef ctx = CGBitmapContextCreate(outBuffer.data, outBuffer.width, outBuffer.height, 8, outBuffer.rowBytes, colorSpace, CGImageGetBitmapInfo(image.CGImage));
    
    CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
    UIImage *returnImage = [UIImage imageWithCGImage:imageRef];
    
    //clean up
    CGContextRelease(ctx);
    CGColorSpaceRelease(colorSpace);
    
    free(pixelBuffer);
    CFRelease(inBitmapData);
    
    CGColorSpaceRelease(colorSpace);
    CGImageRelease(imageRef);
    
    return returnImage;
}


@end
